<template>
	<view class="help-publish-page">
		<view class="page-header">
			<text class="page-title">发布求助</text>
			<text class="page-subtitle">寻求帮助与支持</text>
		</view>

		<view class="form-container">
			<!-- 求助标题 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">求助标题</text>
					<text class="required-mark">*</text>
				</view>
				<up-input 
					v-model="formData.title" 
					placeholder="请简明描述你的问题（10-50字）" 
					:maxlength="50" 
					border="none"
				/>
			</view>

			<!-- 分类、紧急程度 -->
			<view class="form-row">
				<view class="form-item-half">
					<view class="item-label">
						<text class="label-text">求助分类</text>
						<text class="required-mark">*</text>
					</view>
					<view class="selector-input" @click="showCategoryPicker = true">
						<text class="selector-text" :class="{ placeholder: !formData.subCategory }">
							{{ formData.subCategory || '请选择' }}
						</text>
						<up-icon name="arrow-down" size="14" color="#999"></up-icon>
					</view>
				</view>

				<view class="form-item-half">
					<view class="item-label">
						<text class="label-text">时间要求</text>
					</view>
					<view class="selector-input" @click="showUrgencyPicker = true">
						<text class="selector-text" :class="{ placeholder: !formData.urgency }">
							{{ formData.urgency || '请选择' }}
						</text>
						<up-icon name="arrow-down" size="14" color="#999"></up-icon>
					</view>
				</view>
			</view>

			<!-- 酬劳说明 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">酬劳说明</text>
					<text class="label-hint">（选填）</text>
				</view>
				<up-input 
					v-model="formData.reward" 
					placeholder="如：请吃饭、现金20元等" 
					:maxlength="100"
					border="none"
				/>
			</view>

			<!-- 详细描述 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">详细描述</text>
					<text class="required-mark">*</text>
				</view>
				<up-textarea 
					v-model="formData.content" 
					placeholder="请详细描述你遇到的问题（至少20字）" 
					:maxlength="1000"
					count
					:autoHeight="true"
					height="240rpx"
				/>
			</view>

			<!-- 相关图片 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">相关图片</text>
					<text class="label-hint">（选填，最多3张）</text>
				</view>
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in formData.images" :key="index">
						<image :src="image" mode="aspectFill" class="image" />
						<view class="delete-btn" @click="handleDeleteImage(index)">
							<up-icon name="close-circle-fill" color="#fff" size="18"></up-icon>
						</view>
					</view>
					
					<view class="upload-btn" v-if="formData.images.length < 3" @click="handleChooseImage">
						<up-icon name="camera" size="32" color="#999"></up-icon>
					</view>
				</view>
			</view>

			<!-- 联系方式 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">联系方式</text>
					<text class="required-mark">*</text>
				</view>
				<up-input 
					v-model="formData.contactInfo" 
					placeholder="请输入微信号、QQ号或手机号" 
					:maxlength="50"
					border="none"
				/>
			</view>

			<!-- 补充说明 -->
			<view class="form-item">
				<view class="item-label">
					<text class="label-text">补充说明</text>
					<text class="label-hint">（选填）</text>
				</view>
				<up-textarea 
					v-model="formData.note" 
					placeholder="其他需要补充的信息" 
					:maxlength="200"
					count
					:autoHeight="true"
					height="160rpx"
				/>
			</view>

			<!-- 提交按钮 -->
			<view class="submit-container">
				<up-button 
					type="primary" 
					size="large" 
					@click="handleSubmit" 
					:loading="submitting"
					:customStyle="{
						background: 'linear-gradient(135deg, #9F7AEA 0%, #805AD5 100%)',
						border: 'none'
					}"
				>
					{{ submitting ? '发布中...' : '立即发布' }}
				</up-button>
			</view>
		</view>

		<!-- 分类选择器 -->
		<up-picker 
			v-model:show="showCategoryPicker" 
			:columns="categoryColumns"
			@confirm="onCategoryConfirm"
			@cancel="showCategoryPicker = false"
		></up-picker>

		<!-- 紧急程度选择器 -->
		<up-picker 
			v-model:show="showUrgencyPicker" 
			:columns="urgencyColumns"
			@confirm="onUrgencyConfirm"
			@cancel="showUrgencyPicker = false"
		></up-picker>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { mockAddPost } from '../../server/mock.js';

// 表单引用
const formRef = ref(null);
const submitting = ref(false);

// 选择器显示状态
const showCategoryPicker = ref(false);
const showUrgencyPicker = ref(false);

// 表单数据
const formData = reactive({
	title: '',
	subCategory: '学习求助',
	content: '',
	images: [],
	contactInfo: '',
	urgency: '不急',
	reward: '',
	note: ''
});

// 分类选项
const categoryColumns = [
	['学习求助', '生活求助', '技术求助', '情感求助', '其他求助']
];

// 紧急程度选项
const urgencyColumns = [
	['不急', '今天内', '紧急']
];

// 分类确认
const onCategoryConfirm = ({ value }) => {
	formData.subCategory = value[0];
	showCategoryPicker.value = false;
};

// 紧急程度确认
const onUrgencyConfirm = ({ value }) => {
	formData.urgency = value[0];
	showUrgencyPicker.value = false;
};

// 表单验证规则
const rules = {
	title: [
		{ required: true, message: '请输入求助标题', trigger: 'blur' },
		{ min: 10, max: 50, message: '标题长度在 10 到 50 个字符', trigger: 'blur' }
	],
	subCategory: [
		{ required: true, message: '请选择求助分类', trigger: 'change' }
	],
	content: [
		{ required: true, message: '请输入详细描述', trigger: 'blur' },
		{ min: 20, max: 1000, message: '描述长度在 20 到 1000 个字符', trigger: 'blur' }
	],
	contactInfo: [
		{ required: true, message: '请输入联系方式', trigger: 'blur' }
	]
};

/**
 * 选择图片
 */
const handleChooseImage = () => {
	uni.chooseImage({
		count: 3 - formData.images.length,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			formData.images.push(...res.tempFilePaths);
		}
	});
};

/**
 * 删除图片
 */
const handleDeleteImage = (index) => {
	formData.images.splice(index, 1);
};

/**
 * 提交表单
 */
const handleSubmit = async () => {
	// 检查登录状态
	const token = uni.getStorageSync('token');
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}, 1000);
		return;
	}

	// 表单验证
	formRef.value.validate().then(async (valid) => {
		if (valid) {
			submitting.value = true;

			try {
				// 构造帖子数据
				let fullContent = formData.content;
				
				// 添加时间要求
				if (formData.urgency && formData.urgency !== '不急') {
					fullContent += `\n\n【时间要求】${formData.urgency}`;
				}
				
				// 添加酬劳说明
				if (formData.reward) {
					fullContent += `\n【酬劳】${formData.reward}`;
				}
				
				// 添加补充说明
				if (formData.note) {
					fullContent += `\n\n【补充说明】${formData.note}`;
				}

				const postData = {
					title: formData.title,
					content: fullContent,
					image: formData.images,
					plateId: 4, // 求助区板块ID
					subCategory: formData.subCategory,
					helpStatus: 'pending',
					contactInfo: formData.contactInfo,
					helpUrgency: formData.urgency,
					helpReward: formData.reward
				};

				const res = await mockAddPost(postData);

				if (res.code === 200) {
					uni.showToast({
						title: '发布成功',
						icon: 'success'
					});

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.message || '发布失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('发布求助失败:', error);
				uni.showToast({
					title: '发布失败，请重试',
					icon: 'none'
				});
			} finally {
				submitting.value = false;
			}
		}
	}).catch(() => {
		uni.showToast({
			title: '请完善表单信息',
			icon: 'none'
		});
	});
};
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.help-publish-page {
	min-height: 100vh;
	background: $bg-page;

	.page-header {
		background: linear-gradient(135deg, $plate-help 0%, darken($plate-help, 10%) 100%);
		padding: $spacing-xxl;
		padding-top: 120rpx;
		text-align: center;
		color: #fff;

		.page-title {
			font-size: $font-xxl;
			font-weight: $font-bold;
			margin-bottom: $spacing-xs;
		}

		.page-subtitle {
			font-size: $font-sm;
			opacity: 0.9;
		}
	}

	.form-container {
		padding: $spacing-lg;

		.form-item {
			@include card;
			padding: $spacing-lg;
			margin-bottom: $spacing-base;

			.item-label {
				@include flex-between;
				margin-bottom: $spacing-base;

				.label-text {
					font-size: $font-base;
					color: $text-primary;
					font-weight: $font-semibold;
				}

				.required-mark {
					color: $error-color;
					margin-left: $spacing-xs;
				}

				.label-hint {
					font-size: $font-sm;
					color: $text-tertiary;
				}
			}

			.selector-input {
				@include flex-between;
				padding: $spacing-base;
				background: $bg-page;
				border-radius: $radius-base;
				border: 1px solid $border-light;

				.selector-text {
					font-size: $font-base;
					color: $text-primary;
					
					&.placeholder {
						color: $text-tertiary;
					}
				}
			}
		}

		.form-row {
			display: flex;
			gap: $spacing-base;
			margin-bottom: $spacing-base;

			.form-item-half {
				flex: 1;
				@include card;
				padding: $spacing-lg;

				.item-label {
					@include flex-between;
					margin-bottom: $spacing-base;

					.label-text {
						font-size: $font-base;
						color: $text-primary;
						font-weight: $font-semibold;
					}

					.required-mark {
						color: $error-color;
						margin-left: $spacing-xs;
					}
				}

				.selector-input {
					@include flex-between;
					padding: $spacing-base;
					background: $bg-page;
					border-radius: $radius-base;
					border: 1px solid $border-light;

					.selector-text {
						font-size: $font-base;
						color: $text-primary;
						
						&.placeholder {
							color: $text-tertiary;
						}
					}
				}
			}
		}

		.image-list {
			display: flex;
			flex-wrap: wrap;
			gap: $spacing-base;

			.image-item {
				position: relative;
				width: 200rpx;
				height: 200rpx;
				border-radius: $radius-md;
				overflow: hidden;

				.image {
					width: 100%;
					height: 100%;
				}

				.delete-btn {
					position: absolute;
					top: $spacing-xs;
					right: $spacing-xs;
					width: 40rpx;
					height: 40rpx;
					@include flex-center;
					background: rgba(0, 0, 0, 0.6);
					border-radius: $radius-round;
				}
			}

			.upload-btn {
				width: 200rpx;
				height: 200rpx;
				@include flex-center;
				background: $bg-page;
				border: 2rpx dashed $border-base;
				border-radius: $radius-md;

				&:active {
					background: $bg-hover;
					border-color: $plate-help;
				}
			}
		}

		.submit-container {
			margin-top: $spacing-xl;
		}
	}
}
</style>

